import random
import string
import time
import socket
import redis
import jwt
from django.shortcuts import render,HttpResponse,redirect
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from captcha.image import ImageCaptcha
from .models import *
from tools.jwt_decode import login
from works.models import *
# Create your views here.
# 图片验证码
class ImageCodeAPIView(APIView):
    def get(self,request,uuid):
        """验证码为4位字母数字混合
            string.ascii_letters为a-z A-z字母
            string.digits 为0-9数字
            random.sample 是随机取出
        """
        code = "".join(random.sample(string.ascii_letters + string.digits,4))

        # 实例化一个图片验证码
        # 导入captcha.image下的ImageCaptcha 生成图片
        img = ImageCaptcha()

        # 验证码变为图片形式
        img_code = img.generate(code)

        # 启动redis 将验证码存入redis
        rds = redis.Redis(host='localhost',port=6379)
        key = "img_%s"%uuid
        rds.set(key,code,ex=5*60)
        rds.close()

        # 返回响应
        return HttpResponse(img_code,content_type='image/png')


# 用户登录
class UserLoginView(APIView):
    def post(self,request):
        loginForm = request.data.get('loginForm')


        uuid = request.data.get('uuid')

        if not all([loginForm,uuid]):
            return Response({
                'code':400,
                'msg':'数据不完整'
            })

        redis_con = redis.Redis(host='localhost',port=6379)
        key = "img_%s"%uuid
        img_code = redis_con.get(key)
        if not img_code:
            return Response({
                'code':400,
                'msg':'验证码已过期'
            })
        if img_code.decode().lower() != loginForm['code'].lower():
            return Response({
                'code':400,
                'msg':'验证码错误'
            })

        # 找到登录人信息
        user = UserModel.objects.filter(account=loginForm['account']).first()

        # 如果没有登录人信息，返回不存在
        if not user:
            return Response({
                'code':400,
                'msg':'用户不存在'
            })

        # 如果登录人已经离职，返回没有权限登录
        if user.state == 4:
            return Response({
                'code':400,
                'msg':'抱歉，您没有权限登录'
            })

        # 如果有登录人信息，找到对应的账号信息，如果账号和登录人不符合
        if user.account != loginForm['account']:
            return Response({
                'code':400,
                'msg':'账号错误'
            })

        # 如果登录人密码不对，返回密码错误
        if user.password != loginForm['password']:
            return Response({
                'code':400,
                'msg':'密码输入错误'
            })

        # 信息无误，生成token
        token = jwt.encode({
            'uid':user.id,
            'username':user.username,
            'exp':time.time() + 720000
        },key = settings.SECRET_KEY,algorithm='HS256')

        return Response({
            'code':200,
            'msg':'登陆成功',
            'token':token
        })

# 登陆日志
class LoginLogView(APIView):
    @login
    def post(self, request):
        uid = request.uid

        host_name = socket.gethostname()
        ip = socket.gethostbyname(host_name)
        LoginLogModel.objects.create(user_id_id=uid, login_ip=ip, login_equip=host_name)

        return Response({
            'code': 200,
            'msg': "添加成功",
        })

    def get(self,request):
        log = LoginLogModel.objects.all()
        temp = []
        for item in log:
            temp.append({
                'id':item.id,
                'username':item.user_id.username,
                'login_time':str(item.login_time).split('.')[0],
                'login_ip':item.login_ip,
                'login_equip':item.login_equip
            })
        return Response({
            'code':200,
            'msg':'获取成功',
            'data':temp
        })

# 用户管理，查看，增加
class UserManageAPIView(APIView):
    @login
    def get(self,request):
        """
            username
            account
            password
             mobile
            mail
            role_id
            department_id
            rank_id
            posts_id
            state
        """
        # 判断角色的权限
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        print("????",user.role_id_id)

        # 如果用户没有超级管理员权限，就看不了全部员工信息，只能看自己的

        user_all = UserModel.objects.all()
        temp = []
        for i in user_all:
            temp.append({
                'id':i.id,
                'username':i.username,
                'account':i.account,
                'password':i.password,
                'mobile':i.mobile,
                'mail':i.mail,
                'role':i.role_id.role,
                'department':i.department_id.department,
                'posts':i.posts_id.posts,
                'rank':i.rank_id.rank,
                'state':i.state
            })

        return Response({
            'code':200,
            'msg':'获取员工信息成功',
            'user_all':temp,
            'user': {
                'id': user.id,
                'username': user.username,
                'account': user.account,
                'mobile': user.mobile,
                'mail': user.mail,
                'role': user.role_id.role,
                'department': user.department_id.department,
                'rank': user.rank_id.rank,
                'posts': user.posts_id.posts,
                'state': user.state
            }
        })

    @login
    def post(self,request):
        """
        username
        account
        password
        mobile
        mail
        role_id
        department_id
        rank_id
        posts_id
        state
        """
        username = request.data.get('username')
        account = request.data.get('account')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        mail = request.data.get('mail')
        department_id = request.data.get('department_id')
        role_id = request.data.get('role_id')
        rank_id = request.data.get('rank_id')
        posts_id = request.data.get('posts_id')
        state = request.data.get('state')
        if state == '1':
            state='在职'
        elif state == '2':
            state='出差'
        elif state == '3':
            state='请假'
        if not all([username,account,password,mobile,mail,department_id,role_id,rank_id,posts_id,state]):
            return Response({
                'code':400,
                'msg':'输入信息不完整'
            })
        user = UserModel.objects.filter(username=username)
        acc = UserModel.objects.filter(account=account)
        mob = UserModel.objects.filter(mobile=mobile)
        if user or acc or mob:
            return Response({
                'code':400,
                'msg':'信息有重复，请重新输入'
            })
        UserModel.objects.create(username=username,account=account,password=password,mobile=mobile,mail=mail,department_id_id=department_id,role_id_id=role_id,rank_id_id=rank_id,posts_id_id=posts_id,state=state)
        return Response({
            'code':200,
            'msg':'添加用户成功'
        })

class UserManageView(APIView):
    # 获取角色单条信息
    @login
    def get(self,request,id):
        user_one = UserModel.objects.get(id=id)
        if not user_one:
            return Response({
                'code':400,
                'msg':'该员工信息不存在'
            })
        return Response({
            'code':200,
            'msg':'获取该员工信息成功',
            'data':{
                'id':user_one.id,
                'username':user_one.username,
                'account':user_one.account,
                'mobile':user_one.mobile,
                'mail':user_one.mail,
                'departments':user_one.department_id.department,
                'rank':user_one.rank_id.rank,
                'posts':user_one.posts_id.posts
            }
        })
    # 离职
    def delete(self,request,id):
        user_one = UserModel.objects.filter(id=id).first()
        if not user_one:
            return Response({
                'code':400,
                'msg':'未找到该用户'
            })
        user_one.update(state=4)
        return Response({
            'code':200,
            'msg':'用户删除成功'
        })

    # 修改
    def put(self,request,id):
        """
            username
            account
            password
            mobile
            mail
            role_id
            department_id
            rank_id
            posts_id
            state
        """
        username = request.data.get('username')
        account = request.data.get('account')
        mobile = request.data.get('mobile')
        mail = request.data.get('mail')
        department_id = request.data.get('department_id')
        role_id = request.data.get('role_id')
        rank_id = request.data.get('rank_id')
        posts_id = request.data.get('posts_id')
        state = request.data.get('state')
        if state == '1':
            state='在职'
        elif state == '2':
            state='出差'
        elif state == '3':
            state='请假'
        print("????",username, account, mobile, mail, department_id, rank_id, posts_id, state)
        if not all([username, account, mobile, mail, department_id, role_id,rank_id, posts_id, state]):
            return Response({
                'code': 400,
                'msg': '输入信息不完整'
            })
        UserModel.objects.filter(id=id).update(username=username,account=account,mobile=mobile,mail=mail,department_id_id=department_id,role_id_id=role_id,rank_id_id=rank_id,posts_id_id=posts_id,state=state)
        return Response({
            'code':200,
            'msg':'修改成功'
        })


# 部门查询，增加
class DepartmentAPIView(APIView):
    @login
    # 部门查询
    def get(self,request):
        uid = request.uid
        depart_all = DepartmentModel.objects.all()
        temp = []
        for i in depart_all:
            temp.append({
                'id':i.id,
                'department':i.department
            })
        return Response({
            'code':200,
            'msg':'获取部门成功',
            'departments':temp
        })

    # 部门增加
    @login
    def post(self,request):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code':400,
                'msg':'抱歉，您没有权限'
            })

        # 前段获取数据
        department_name = request.data.get('department')
        DepartmentModel.objects.create(department=department_name)
        return Response({
            'code':200,
            'msg':'部门添加成功'
        })

# 部门修改，删除
class DepartmentView(APIView):
    # 单条查询
    def get(self, request, id):
        department_one = DepartmentModel.objects.get(id=id)
        return Response({
            'code': 200,
            'msg': '获取单条部门成功',
            'data': {
                'id': department_one.id,
                'department': department_one.department
            }
        })
    @login
    # 部门删除
    def delete(self,request,id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        else:
            DepartmentModel.objects.filter(id=id).delete()

        return Response({
            'code':200,
            'msg':'部门删除成功'
        })

    # 部门修改
    @login
    def put(self,request,id):
        department = request.data.get('department')
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        else:
            DepartmentModel.objects.filter(id=id).update(department=department)

        return Response({
            'code':200,
            'msg':'修改部门成功'
        })

# 岗位查询，增加
class PostsAPIView(APIView):
    @login
    # 岗位查询
    def get(self, request):
        uid = request.uid
        post_all = PostModel.objects.all()
        temp = []
        for i in post_all:
            temp.append({
                'id': i.id,
                'posts': i.posts
            })
        return Response({
            'code': 200,
            'msg': '获取岗位成功',
            'posts': temp
        })

    # 岗位增加
    @login
    def post(self, request):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        posts_name = request.data.get('posts')
        PostModel.objects.create(posts=posts_name)
        return Response({
            'code':200,
            'msg':'岗位添加成功'
        })

# 岗位修改，删除
class PostsView(APIView):
    # 单条查询
    def get(self, request, id):
        posts_one = PostModel.objects.get(id=id)
        return Response({
            'code': 200,
            'msg': '获取单条岗位成功',
            'data': {
                'id': posts_one.id,
                'posts': posts_one.posts
            }
        })
    @login
    # 岗位删除
    def delete(self, request, id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        else:
            PostModel.objects.filter(id=id).delete()

        return Response({
            'code': 200,
            'msg': '岗位删除成功'
        })

    # 岗位修改
    @login
    def put(self, request, id):
        posts = request.data.get('posts')
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        else:
            PostModel.objects.filter(id=id).update(posts=posts)

        return Response({
            'code': 200,
            'msg': '修改岗位成功'
        })


# 职级查询，增加
class RankAPIView(APIView):
    @login
    # 职级查询
    def get(self, request):
        uid = request.uid
        rank_all = RankModel.objects.all()
        temp = []
        for i in rank_all:
            temp.append({
                'id': i.id,
                'rank': i.rank
            })
        return Response({
            'code': 200,
            'msg': '获取职级成功',
            'rank': temp
        })

    # 职级增加
    @login
    def post(self, request):
        rank_name = request.data.get('rank')
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })

        RankModel.objects.create(rank=rank_name)
        return Response({
            'code':200,
            'msg':'添加职级成功'
        })

# 职级单条查询，修改，删除
class RankView(APIView):
    # 单条查询
    def get(self,request,id):
        rank_one = RankModel.objects.get(id=id)
        return Response({
            'code':200,
            'msg':'获取单条职级成功',
            'data':{
                'id':rank_one.id,
                'rank':rank_one.rank
            }
        })
    @login
    # 职级删除
    def delete(self, request, id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        else:
            RankModel.objects.filter(id=id).delete()

        return Response({
            'code': 200,
            'msg': '职级删除成功'
        })

    # 职级修改
    @login
    def put(self, request, id):
        uid = request.uid
        rank = request.data.get('rank')
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        else:
            RankModel.objects.filter(id=id).update(rank=rank)

        return Response({
            'code': 200,
            'msg': '修改职级成功'
        })

# 角色管理 查看，添加
class RoleAPIView(APIView):
    # 查看所有角色
    @login
    def get(self,request):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        role_all = RoleModel.objects.all()
        temp = []
        for i in role_all:
            temp.append({
                'id':i.id,
                'role':i.role,
                'per_id':i.per_id.permission
            })
        return Response({
            'code':200,
            'msg':'获取角色信息成功',
            'role':temp
        })

    @login
    def post(self,request):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        role = request.data.get('role')
        per_id = request.data.get('per_id')
        if not all([role,per_id]):
            return Response({
                'code':400,
                'msg':'输入信息不完整'
            })
        RoleModel.objects.create(role=role,per_id_id=per_id)
        return Response({
            'code':200,
            'msg':'角色添加成功'
        })

# 角色单条查询，修改，删除
class RoleView(APIView):
    # 查询单条角色
    @login
    def get(self,request,id):
        role_one = RoleModel.objects.get(id=id)
        return Response({
            'code':200,
            'msg':'获取单条角色成功',
            'role':{
                'id':role_one.id,
                'role':role_one.role,
                'permission':role_one.per_id.permission
            }
        })

    # 删除
    def delete(self,request,id):
        RoleModel.objects.get(id=id).delete()
        return Response({
            'code':200,
            'msg':'删除成功'
        })

    # 修改
    def put(self,request,id):
        role = request.data.get('role')
        per_id = request.data.get('per_id')
        if not all([role,per_id]):
            return Response({
                'code':400,
                'msg':'输入信息不完整'
            })
        RoleModel.objects.filter(id=id).update(role=role,per_id_id=per_id)
        return Response({
            'code':200,
            'msg':'角色修改成功'
        })

# 权限查看，添加
class PermissionAPIView(APIView):
    # 查看
    @login
    def get(self,request):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        per_all = PermissionModel.objects.all()
        temp = []
        for i in per_all:
            temp.append({
                'id':i.id,
                'permission':i.permission,
                'per_url':i.per_url
            })
        return Response({
            'code':200,
            'msg':'获取权限成功',
            'data':temp
        })

    # 添加
    @login
    def post(self,request):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        permission = request.data.get('permission')
        per_url = request.data.get('per_url')
        if not all([permission,per_url]):
            return Response({
                'code':400,
                'msg':'输入信息不完整'
            })
        PermissionModel.objects.create(permission=permission,per_url=per_url)
        return Response({
            'code':200,
            'msg':'权限添加成功'
        })

# 权限单条信息查看，修改，删除
class PermissionView(APIView):
    # 查看单条
    @login
    def get(self,request,id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        per_one = PermissionModel.objects.get(id=id)
        return Response({
            'code':200,
            'msg':'获取单条权限成功',
            'data':{
                'id':per_one.id,
                'permission':per_one.permission,
                'per_url':per_one.per_url
            }
        })

    # 修改
    @login
    def put(self,request,id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        permission = request.data.get('permission')
        per_url = request.data.get('per_url')
        if not all([permission,per_url]):
            return Response({
                'code':400,
                'msg':'输入信息不完整'
            })
        PermissionModel.objects.filter(id=id).update(permission=permission,per_url=per_url)
        return Response({
            'code':200,
            'msg':'修改权限成功'
        })
        
    # 删除
    @login
    def delete(self,request,id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        PermissionModel.objects.get(id=id).delete()
        return Response({
            'code':200,
            'msg':'权限删除成功'
        })


# 车辆信息查询，增加
class CarAPIView(APIView):
    @login
    # 车辆查询
    def get(self, request):
        """ car_name
            car_type
            car_num
        """
        uid = request.uid
        car_all = CarMessageModel.objects.all()
        temp = []
        for i in car_all:
            temp.append({
                'id': i.id,
                'car_name': i.car_name,
                'car_type':i.car_type,
                'car_num':i.car_num
            })
        return Response({
            'code': 200,
            'msg': '获取车辆信息成功',
            'cars': temp
        })

    # 车辆增加
    @login
    def post(self, request):
        uid = request.uid
        car_name = request.data.get('car_name')
        car_type = request.data.get('car_type')
        car_num = request.data.get('car_num')
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })

        cars = CarMessageModel.objects.filter(car_num=car_num).first()
        if not cars:
            try:
                CarMessageModel.objects.create(car_name=car_name,car_type=car_type,car_num=car_num)
                return Response({
                    'code':200,
                    'msg':'添加车辆成功'
                })
            except Exception as e:
                print('添加失败的原因是：', e)
                return Response({
                    'code': 400,
                    'msg': '添加失败'
                })
        else:
            return Response({
                'code': 400,
                'msg': '车牌号已存在'
            })

# 车辆修改，删除
class CarView(APIView):
    # 车辆单条查询
    @login
    def get(self,request,id):
        car_one = CarMessageModel.objects.get(id=id)
        return Response({
            'code':200,
            'msg':'获取单条车辆信息成功',
            'data':{
                'id':car_one.id,
                'car_name':car_one.car_name,
                'car_type':car_one.car_type,
                'car_num':car_one.car_num
            }
        })
    @login
    # 车辆删除
    def delete(self, request, id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        else:
            CarMessageModel.objects.filter(id=id).delete()

        return Response({
            'code': 200,
            'msg': '车辆删除成功'
        })

    # 车辆修改
    @login
    def put(self, request, id):
        uid = request.uid
        car_name = request.data.get('car_name')
        car_type = request.data.get('car_type')
        car_num = request.data.get('car_num')
        if not all([car_name,car_type,car_num]):
            return Response({
                'code':400,
                'msg':'输入信息不完整'
            })
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        CarMessageModel.objects.filter(id=id).update(car_name=car_name,car_type=car_type,car_num=car_num)

        return Response({
            'code': 200,
            'msg': '修改车辆成功'
        })


